package com.itzhihao.controller;

import com.itzhihao.entity.Cart;
import com.itzhihao.service.ICartService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController extends BaseController {

    @Resource
    private ICartService cartService;

    @PostMapping("/list")
    public TableDataInfo getList(@RequestBody PageDomain pageDomain){
        return cartService.getList(pageDomain);
    }

    /**
     * 查看购物车详情
     * @param id
     * @return
     */
    @GetMapping
    public AjaxResult getDetail(@RequestParam(value = "cart_id") Long id){
        Cart cart = cartService.getDetail(id);
        return success(cart);
    }

    @PutMapping
    public AjaxResult update(@RequestBody Cart cart){
        boolean isUpdate = cartService.updateOrSave(cart);
        if(isUpdate){
            return AjaxResult.success("更新成功");
        }else{
            return AjaxResult.error("更新失败，请重试");
        }
    }

    @DeleteMapping("/delete/{cart_id}")
    public AjaxResult delete(@PathVariable(value = "cart_id") Long id){
        boolean isDelete = cartService.deleteById(id);
        if(isDelete){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败，请重试");
        }
    }

    /**
     * 新增
     * @param cart
     * @return
     */
    @PostMapping
    public AjaxResult add(@RequestBody Cart cart){
        boolean isSave = cartService.updateOrSave(cart);
        if (isSave){
            return AjaxResult.success("保存成功");
        }else{
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Delete("/delete/{ids}")
    public AjaxResult deleteBatch(@PathVariable String ids){
        Long[] idLongArr = Convert.toLongArray(ids);
        List<Long> idLongList = Arrays.asList(idLongArr);
        boolean isDelete = cartService.deleteByIds(idLongList);
        if(isDelete){
            return success("批量删除成功");
        }else{
            return error("批量删除失败");
        }
    }
}
